<template>
  <div class="home" ref="homeRef">
    <van-tabs title-active-color="#ff0">
      <van-tab
        v-for="category in categoryList"
        :title="category.name"
        :key="category.id">
      </van-tab>
    </van-tabs>

    <!-- 轮播图 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item
        v-for="banner in banners"
        :key="banner.id"
      >
        <img class="swipe-image" :src="banner.imageUrl" />
        <!-- {{ banner.image_url }} -->
      </van-swipe-item>
    </van-swipe>

    <!-- 分隔线 -->
    <van-divider>爆款商品</van-divider>

    <!-- 渲染商品数据 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-card
        v-for="item in baokuan"
        :key="item.id"
        :thumb="item.image"
        :title="item.title"
        :price="item.price | money"
        :origin-price="item.originPrice | money"
        @click="jumpToDetail(item.detailUrl)"
      >
        <template v-slot:num>
          <div>
            <span>月销售数量：{{ item.saleNum | saleNum }}</span>
            <van-icon name="shopping-cart-o" color="red" size="18px" @click.stop="handleAddToCart(item)" />
          </div>
        </template>
        <template #desc>
          <div class="ranking">排行：{{ item.rankingTag }}</div>
        </template>
      </van-card>
    </van-list>

    <div class="top" v-show="topShow" @click="backToTop">TOP</div>
  </div>
</template>

<script>
import { getCategories, getBanners, getBaoKuanItems } from '@/api/home'

export default {
  name: 'Home',
  data () {
    return {
      categoryList: [],
      banners: [],
      baokuan: [],
      loading: false,
      finished: false,
      nextIndex: 0,
      topShow: false
    }
  },
  computed: {
    parent () {
      // console.log('computed...', this.$refs.homeRef.parentNode)
      return this.$refs.homeRef.parentNode
    }
  },
  async created () {
    // 先获取本地缓存的分类数组
    const categories = JSON.parse(sessionStorage.getItem('categories'))
    if (categories) { // 有缓存的数组，则直接使用
      this.categoryList = categories
    } else { // 没有缓存的数组，则发送请求，然后将返回的数组缓存到 sessionStorage 中
      const p1 = getCategories()
      const categories = await p1
      // 将读取到的分类数组缓存到 sessionStorage 中
      sessionStorage.setItem('categories', JSON.stringify(categories.list))
      this.categoryList = categories.list
    }

    const p2 = getBanners()
    const banners = await p2
    this.banners = banners.banners
  },
  mounted () {
    const that = this
    this.parent.onscroll = function () {
      that.topShow = this.scrollTop >= 1200
    }
  },
  beforeDestroy () {
    // 将 DOM 元素上绑定的滚动事件销毁
    this.parent.onscroll = null
  },
  methods: {
    // 加载更多商品数据
    async onLoad () {
      const baokuan = await getBaoKuanItems(this.nextIndex)
      // this.baokuan = [...this.baokuan, ...baokuan.list]
      this.baokuan.push(...baokuan.list)
      this.nextIndex = baokuan.nextIndex
      this.finished = baokuan.isEnd
      this.loading = false
    },
    // 跳转到详情页面
    jumpToDetail (detailUrl) {
      this.$router.push({
        name: 'detail',
        params: {
          id: detailUrl.slice(detailUrl.lastIndexOf('=') + 1)
        }
      })
    },
    // 处理添加到购物车
    handleAddToCart (prod) {
      const { id, image, title, price } = prod
      // 当前选购商品对象
      const current = {
        id,
        image,
        title,
        price,
        amount: 1
      }
      // 将当前选购商品保存到 store 的 state 中：提交 mutation
      this.$store.commit('addToCart', current)
      // console.log(current)

      // console.log('$store::::', this.$store)
    },
    // 回到顶部
    backToTop () {
      this.$refs.homeRef.parentNode.scrollTop = 0
    }
  }
}
</script>

<style lang="less" scoped>
  // 样式穿透
  /deep/ .van-tabs__line {
    background-color: #000;
  }
  .swipe-image {
    width: 100%;
  }
  .ranking {
    color: red;
  }
  .top {
    width: 48px;
    height: 48px;
    background: #00f;
    color: #fff;
    position: fixed;
    right: 20px;
    bottom: 120px;
    border-radius: 60px;
    text-align: center;
    line-height: 48px;
  }
</style>
